package com.example.administrator.szb.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by D N on 2017/10/10.
 */

public class SharedPreferencesUtil {
    static SharedPreferences sharedPreferences;
    /**
     * 保存数据
     */
    public static void savaData(Context context,Object o,String key){
        try {
            sharedPreferences = context.getSharedPreferences("base64", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(o);
            String base64Product = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
            editor.putString(key, base64Product);//保存对象
            editor.commit();
        }catch (Exception e){
            Toasts.show(context, ""+e.toString(), Toast.LENGTH_SHORT);
        }

    }

    /**
     * 取出数据
     */
    public static Object getData(Context context,String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences("base64", MODE_PRIVATE);
        String productString = sharedPreferences.getString(key, "");
        byte[] base64Product = Base64.decode(productString, Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(base64Product);
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(bais);
            Object o = (Object) ois.readObject();
            return o;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

}
